package 力扣_数学思维题;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zx
 * @create 2022-05-07 18:30
 */
public class 多数元素_169 {
    /**
     * @return 摩尔投票法
     * 关于摩尔投票法的证明请看此题leetcode官方题解
     */
    public int majorityElement(int[] nums) {
        int count = 0;
        int candidate = 0;

        for (int i = 0;i < nums.length;i++) {
            if (count == 0) {
                candidate = nums[i];
            }
            if(nums[i] == candidate){
                count++;
            }else{
                count--;
            }
        }

        return candidate;
    }

    /**
     * @return 哈希表
     */
    public int majorityElement2(int[] nums) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int i = 0;i < nums.length;i++){
            if(map.containsKey(nums[i])){
                map.put(nums[i],map.get(nums[i]) + 1);
            }else{
                map.put(nums[i],1);
            }
        }
        int maxValue = Integer.MIN_VALUE;
        int max = 0;
        for(Map.Entry<Integer,Integer> entry : map.entrySet()){
            if(maxValue < entry.getValue()){
                maxValue = entry.getValue();
                max = entry.getKey();
            }
        }
        return max;
    }

    /**
     * @return 排序
     */
    public int majorityElement3(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length / 2];
    }
}
